package com.chhuang.ewcrm.controller;

import com.chhuang.ewcrm.bean.QueryBean;
import com.chhuang.ewcrm.config.EwcrmProperties;
import com.chhuang.ewcrm.consts.EwcrmConstants;
import com.chhuang.ewcrm.entity.SysUser;
import com.chhuang.ewcrm.file.FileUtil;
import com.chhuang.ewcrm.service.SysUserService;
import com.chhuang.ewcrm.string.Md5Util;
import com.chhuang.ewcrm.vo.ResultBean;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * @author chhuang
 * @create 2020-11-17-9:08
 */
@RestController
@RequestMapping("/wapi/sysUser")
public class WUserController {
    Logger logger= LoggerFactory.getLogger(WUserController.class);

    /**
     * 服务对象
     */
    @Resource
    private SysUserService sysUserService;
    @Autowired
    private EwcrmProperties ewcrmProperties;

    /**
     * 获取负责人
     * @return
     */
    @GetMapping("/getChargerMans")
    public ResultBean<List<SysUser>> getChargerMans(){
        ResultBean<List<SysUser>> resultBean = new ResultBean<>();

        List<SysUser> sysUsers = new LinkedList<>();

        SysUser sysUser = new SysUser();
        String[] roleIds = {"002","003","004","005"};//负责人角色编号
        for (String id : roleIds){
            sysUser.setRoleId(id);
            List<SysUser> users = sysUserService.query(sysUser,"create_time");
            if(users!=null && !users.isEmpty()){
                sysUsers.addAll(users);
            }
        }

        resultBean.setSuccess(true);
        resultBean.setData(sysUsers);
        return resultBean;
    }

    /**
     * 获取业务员
     * @return
     */
    @GetMapping("/getSalesmans")
    public ResultBean<List<SysUser>> getSalesmans(){
        ResultBean<List<SysUser>> resultBean = new ResultBean<>();
        SysUser sysUser = new SysUser();
        sysUser.setRoleId("004");
        resultBean.setData(sysUserService.query(sysUser, "create_time"));
        resultBean.setSuccess(true);
        return resultBean;
    }

    /**
     * 检验用户名不为空或者是否已存在
     * @param username
     * @return
     */
    @GetMapping("/checkUsername")
    public ResultBean<?> checkUsername(String userId, String username){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(username)){
            SysUser u = new SysUser();
            u.setUsername(username);
            List<SysUser> users = this.sysUserService.query(u);
            if(users==null || users.isEmpty() || users.get(0).getUserId().equals(userId)) //用户名不存在
                resultBean.setSuccess(true);
            else
                resultBean.setMessage("用户名已存在");
        }else
            resultBean.setMessage("用户名不为空");

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 检验用户手机号不为空或者已存在
     * @param userphone
     * @return
     */
    @GetMapping("/checkPhone")
    public ResultBean<?> checkPhone(String userId, String userphone){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(userphone)) {//手机号不为空
            SysUser u = new SysUser();
            u.setUserphone(userphone);
            List<SysUser> users = this.sysUserService.query(u);
            if (users == null || users.isEmpty() || users.get(0).getUserId().equals(userId)) //手机号不存在
                resultBean.setSuccess(true);
            else
                resultBean.setMessage("手机号已存在");
        }else
            resultBean.setMessage("手机号不为空");

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 检验邮箱号不为空或者已存在
     * @param email
     * @return
     */
    @GetMapping("/checkEmail")
    public ResultBean<?> checkEmail(String userId, String email){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(true);

        if(StringUtils.isNotEmpty(email)) {//邮箱号允许为空
            SysUser u = new SysUser();
            u.setEmail(email);
            List<SysUser> users = this.sysUserService.query(u);
            if(users!=null && !users.isEmpty() && !users.get(0).getUserId().equals(userId)) { //邮箱已存在
                resultBean.setSuccess(false);
                resultBean.setMessage("邮箱已存在");
            }
        }

        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 修改用户信息
     * @param sysUser
     * @return
     */
    @PutMapping("/editUserInfo")
    public ResultBean<SysUser> editUserInfo(@RequestBody SysUser sysUser, @RequestHeader("Authorization") String authorization){
        ResultBean<SysUser> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);
        resultBean.setMessage("参数为空 或者 用户还没有登录过磅软件");

        if(sysUser!=null && StringUtils.isNotEmpty(authorization) && authorization.startsWith("Weigh")){
            String token = authorization.split(" ")[1];
            if(StringUtils.isNotEmpty(token)){
                SysUser user = new SysUser();
                user.setWsLoginToken(token);
                List<SysUser> users = sysUserService.query(user);
                if(users!=null && !users.isEmpty()){
                    user = users.get(0);
                    if (user != null && checkUsername(user.getUserId(), sysUser.getUsername()).isSuccess()
                            && checkPhone(user.getUserId(), sysUser.getUserphone()).isSuccess()
                            && checkEmail(user.getUserId(), sysUser.getEmail()).isSuccess()) {
                        //密码默认不修改
//                        user.setUsername(sysUser.getUsername()); 不能修改用户名，或者 密码需要初始化
                        user.setFullname(sysUser.getFullname());
                        user.setUserphone(sysUser.getUserphone());
                        user.setUsersphone(sysUser.getUsersphone());
                        user.setUserphoto(sysUser.getUserphoto());
                        user.setEmail(sysUser.getEmail());
                        user.setModifyTime(new Date());
                        resultBean.setData(sysUserService.update(user));
                        resultBean.setSuccess(true);
                        resultBean.setMessage(null);
                    }else
                        resultBean.setMessage("用户不存在，或者用户名、手机号、邮箱号已存在");
                }
            }
        }

        logger.debug(resultBean.toString());
        return resultBean;
    }


    /**
     * 用户信息保存成功后，上传头像
     * @param userId
     * @param userphoto
     * @return
     */
    @PostMapping("/uploadPhoto")
    public ResultBean<String> uploadPhoto(String userId, MultipartFile userphoto) throws IOException {
        ResultBean<String> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(userId) && userphoto!=null && !userphoto.isEmpty() ){
            SysUser sysUser = sysUserService.queryById(userId);
            if(sysUser!=null) {
                String filename = userphoto.getOriginalFilename();//原文件名
                String suffixName = FileUtil.getFileSuffix(filename);//后缀名
                filename = "userphotos/" + sysUser.getUsername() + "." + suffixName;
                String userphotoPath = ewcrmProperties.getUploadPath() + filename;

                File file = new File(userphotoPath);
                FileUtil.makeFilePath(file);
                userphoto.transferTo(file);

                sysUser.setUserphoto(EwcrmConstants.UPLOAD_URL + filename);
                sysUser.setModifyTime(new Date());
                sysUser = this.sysUserService.update(sysUser);
                resultBean.setData(sysUser.getUserphoto());
                resultBean.setSuccess(true);
            }else{
                resultBean.setMessage("用户不存在");
            }
        }else {
            resultBean.setMessage("参数不能为空");
        }

        return resultBean;
    }

    /**
     * 修改自己的密码
     * @param oldPassword
     * @param password
     * @param confirmPassword
     * @return
     */
    @PostMapping("/updateUserPassword")
    public ResultBean<?> updateUserPassword(String oldPassword, String password, String confirmPassword,
                                                  @RequestHeader("Authorization") String authorization){
        ResultBean<?> resultBean = new ResultBean<>();
        resultBean.setSuccess(false);

        if(StringUtils.isNotEmpty(oldPassword)
                && StringUtils.isNotEmpty(password)
                && StringUtils.isNotEmpty(confirmPassword)
                &&StringUtils.isNotEmpty(authorization) && authorization.startsWith("Weigh")) {
            String token = authorization.split(" ")[1];
            if(StringUtils.isNotEmpty(token)) {
                SysUser user = new SysUser();
                user.setWsLoginToken(token);
                List<SysUser> users = sysUserService.query(user);
                if (users != null && !users.isEmpty()) {
                    user = users.get(0);
                    if (confirmPassword.equals(password)) {
                        oldPassword = Md5Util.md5(oldPassword, Md5Util.md5(user.getUsername()));
                        if(user.getPassword().equals(oldPassword)) {
                            user.setPassword(Md5Util.md5(password, Md5Util.md5(user.getUsername())));
                            this.sysUserService.update(user);
                            resultBean.setSuccess(true);
                        }else {
                            resultBean.setMessage("原密码不正确");
                        }
                    } else {
                        resultBean.setMessage("新密码与确认密码不一致");
                    }
                }else
                    resultBean.setMessage("无法找到此用户");
            }else
                resultBean.setMessage("你还没有登录");
        }else {
            resultBean.setMessage("参数不为空");
        }
        logger.debug(resultBean.toString());
        return resultBean;
    }

    /**
     * 获取所有过磅员
     * @return
     */
    @PostMapping("/getWeighers")
    public ResultBean<PageInfo<SysUser>> getWeighers(@RequestBody QueryBean<SysUser> queryBean){
        ResultBean<PageInfo<SysUser>> resultBean = new ResultBean<>();
        resultBean.setSuccess(true);

        PageInfo<SysUser> pageInfo = null;
        List<SysUser> users = null;
        if(queryBean!=null) {
            SysUser query = queryBean.getQuery();
            if(query==null) query = new SysUser();
            query.setRoleId("005");//过磅员
            queryBean.setQuery(query);

            if (StringUtils.isNotEmpty(queryBean.getOrderBy()))
                pageInfo = sysUserService.queryLike(queryBean.getQuery(), queryBean.getPageNum(), queryBean.getPageSize(), queryBean.getOrderBy());
            else
                pageInfo = sysUserService.queryLike(queryBean.getQuery(), queryBean.getPageNum(), queryBean.getPageSize());
            resultBean.setData(pageInfo);
        }else {
            users = sysUserService.queryLike(null);
            pageInfo = new PageInfo<>();
            pageInfo.setList(users);
            resultBean.setData(pageInfo);
        }
        resultBean.setSuccess(true);
        resultBean.setCode(queryBean.getDraw());

        return resultBean;
    }
}
